<template>
  <div class="content-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>测试视频管理</span>
          
        </div>
      </template>
      
      <div class="content-body">
        <!-- 搜索栏 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.title" 
            placeholder="请输入标题搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-select v-model="queryForm.testType" placeholder="测试类型" style="width: 120px; margin-right: 10px;" clearable>
            <el-option label="全部" value="" />
            <el-option label="技术测试" value="技术测试" />
            <el-option label="体能测试" value="体能测试" />
            <el-option label="战术测试" value="战术测试" />
            <el-option label="比赛测试" value="比赛测试" />
          </el-select>
          <el-select v-model="queryForm.difficulty" placeholder="难度等级" style="width: 120px; margin-right: 10px;" clearable>
            <el-option label="全部" value="" />
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
          </el-select>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="handleAdd"><el-icon><plus /></el-icon> 添加测试视频</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;" v-loading="loading">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="title" label="标题" min-width="200" />
          <el-table-column prop="testType" label="测试类型" width="100" />
          <el-table-column prop="difficulty" label="难度等级" width="100" />
          <el-table-column prop="duration" label="时长" width="80" />
          <el-table-column prop="description" label="测试说明" min-width="200" show-overflow-tooltip />
          <el-table-column label="视频预览" width="100">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="previewVideo(row)">播放</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加测试视频' : '编辑测试视频'"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入测试视频标题" />
        </el-form-item>
        <el-form-item label="测试类型" prop="testType">
          <el-select v-model="form.testType" placeholder="请选择测试类型" style="width: 100%">
            <el-option label="技术测试" value="技术测试" />
            <el-option label="体能测试" value="体能测试" />
            <el-option label="战术测试" value="战术测试" />
            <el-option label="比赛测试" value="比赛测试" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级" prop="difficulty">
          <el-select v-model="form.difficulty" placeholder="请选择难度等级" style="width: 100%">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
          </el-select>
        </el-form-item>
        <el-form-item label="测试时长" prop="duration">
          <el-input v-model="form.duration" placeholder="请输入测试时长，如：5分钟" />
        </el-form-item>
        <el-form-item label="测试说明" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入测试说明" />
        </el-form-item>
        <el-form-item label="测试要求" prop="requirements">
          <el-input v-model="form.requirements" type="textarea" :rows="4" placeholder="请输入测试要求和评分标准" />
        </el-form-item>
        <el-form-item label="视频上传" prop="videoUrl">
          <el-upload
            class="video-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept="video/*"
          >
            <div v-if="!form.videoUrl">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽视频到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="video-preview">
              <video :src="form.videoUrl" controls class="uploaded-video" />
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeVideo"
              >
                删除视频
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog v-model="videoDialogVisible" title="测试视频预览" width="800px">
      <div v-if="currentVideo">
        <video :src="currentVideo.videoUrl" controls width="100%" height="400"></video>
        <div style="margin-top: 15px;">
          <h4>{{ currentVideo.title }}</h4>
          <p><strong>测试类型：</strong>{{ currentVideo.testType }}</p>
          <p><strong>难度等级：</strong>{{ currentVideo.difficulty }}</p>
          <p><strong>测试说明：</strong>{{ currentVideo.description }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, UploadFilled, Search } from '@element-plus/icons-vue'
import { testvideoList, testvideoAddOrUpdate, testvideoDelete } from '@/request/testvideo.js'

// 数据相关
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 搜索表单
const queryForm = reactive({
  title: '',
  testType: '',
  difficulty: '',
  pageNum: 1,
  pageSize: 10
})

const getList = ()=>{
  loading.value = true
  testvideoList(queryForm).then(res=>{
    loading.value = false
    tableData.value = res.records
    total.value = res.total
  }).catch(err=>{
    loading.value = false
  })
}

getList();


// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  title: '',
  testType: '',
  difficulty: '',
  duration: '',
  description: '',
  requirements: '',
  videoUrl: ''
})

// 视频预览
const videoDialogVisible = ref(false)
const currentVideo = ref(null)

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入测试视频标题', trigger: 'blur' }],
  testType: [{ required: true, message: '请选择测试类型', trigger: 'change' }],
  difficulty: [{ required: true, message: '请选择难度等级', trigger: 'change' }],
  duration: [{ required: true, message: '请输入测试时长', trigger: 'blur' }],
  description: [{ required: true, message: '请输入测试说明', trigger: 'blur' }],
  requirements: [{ required: true, message: '请输入测试要求', trigger: 'blur' }],
  videoUrl: [{ required: true, message: '请上传测试视频', trigger: 'change' }]
}

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

// 重置搜索
const resetSearch = () => {
  queryForm.title = ''
  queryForm.testType = ''
  queryForm.difficulty = ''
  getList();
}

// 分页
const handleSizeChange = (val) => {
  queryForm.pageSize = val
  getList();
}

const handleCurrentChange = (val) => {
  queryForm.pageNum = val
  getList();
}

// 添加
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  form.videoUrl = '/api' + form.videoUrl
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该测试视频吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    testvideoDelete(row.id).then(res => {
      ElMessage.success('删除成功')
      getList()
    }).catch(error => {
      ElMessage.error('网络错误，请重试')
    })
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      // 提交时检查
      if (!form.videoUrl) {
        ElMessage.error('请上传测试视频！')
        return
      }
      submitLoading.value = true
      // 创建提交表单数据的副本，避免直接修改原表单
      const submitData = { ...form }
      // 处理视频URL格式 - 只有API返回的URL需要去掉/api前缀
      if (submitData.videoUrl && submitData.videoUrl.startsWith('/api')) {
        submitData.videoUrl = submitData.videoUrl.substring(4)
      }
      console.log(submitData)
      testvideoAddOrUpdate(submitData).then(res => {
        submitLoading.value = false
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
          dialogVisible.value = false
          resetForm()
          getList()
      }).catch(error => {
        console.log(error)
        submitLoading.value = false
        ElMessage.error('网络错误，请重试')
      })
    }
  })
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.title = ''
  form.testType = ''
  form.difficulty = ''
  form.duration = ''
  form.description = ''
  form.requirements = ''
  form.videoUrl = ''
}

// 视频预览
const previewVideo = (row) => {
  // 确保视频URL格式正确
  if (row.videoUrl && !row.videoUrl.startsWith('/api')) {
    row.videoUrl = '/api' + row.videoUrl
  }
  currentVideo.value = row
  videoDialogVisible.value = true
}

// 上传相关
const handleUploadSuccess = (response, file) => {
  console.log('视频上传响应:', response)
  if (response && response.data) {
    form.videoUrl = '/api' + response.data
  } else {
    // 创建本地URL用于预览，但实际提交时可能需要调整
    form.videoUrl = URL.createObjectURL(file.raw)
  }
  console.log('当前表单数据:', form)
  ElMessage.success('视频上传成功')
}

const handleUploadError = () => {
  ElMessage.error('上传失败')
}

const beforeUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt100M = file.size / 1024 / 1024 < 100

  if (!isVideo) {
    ElMessage.error('只能上传视频文件！')
    return false
  }
  if (!isLt100M) {
    ElMessage.error('视频大小不能超过 100MB！')
    return false
  }
  return true
}

const removeVideo = () => {
  form.videoUrl = ''
}

</script>

<style scoped>
.content-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-size: 18px;
  font-weight: bold;
}

.search-filter {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.video-upload {
    width: 100%;
  }

  .video-preview {
    text-align: center;
    margin-top: 10px;
  }

  .uploaded-video {
    width: 100%;
    max-height: 300px;
    margin-bottom: 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 5px;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }
</style>